#pragma once
#include<iostream>
#include<string>
#include<vector>
#include<pthread.h>
#include <semaphore.h>


using namespace std;

template<class T>
class RingQueue
{
public:
    void P(sem_t& sem)
    {
        sem_wait(&sem);
    }
    void V(sem_t& sem)
    {
        sem_post(&sem);
    }
    void Lock(pthread_mutex_t& mutex)
    {
        pthread_mutex_lock(&mutex);
    }
    void Unlock(pthread_mutex_t& mutex)
    {
        pthread_mutex_unlock(&mutex);
    }
public:
    RingQueue(int maxcap=5):maxcap_(maxcap),ringqueue_(maxcap),c_index_(0),p_index_(0)
    {
        sem_init(&cdata_sem_,0,0);
        sem_init(&pspace_sem_,0,maxcap);
        pthread_mutex_init(&c_mutex_,nullptr);
        pthread_mutex_init(&p_mutex_,nullptr);
    }

    void Push(const T& in)//生产
    {
        P(pspace_sem_);//生产者关注空间资源，申请空间资源，空间资源--

        Lock(p_mutex_);//下标也是共享资源，需要加锁保护
        ringqueue_[p_index_]=in;
        p_index_++;
        p_index_%=maxcap_;//维持环形特性
        Unlock(p_mutex_);

        V(cdata_sem_);//数据资源增多了，数据资源++

    }
    void Pop(T* out)//消费
    {
        P(cdata_sem_);//消费者关注数据资源，申请数据资源，数据资源--

        Lock(c_mutex_);//下标也是共享资源，需要加锁保护
        *out=ringqueue_[c_index_];
        c_index_++;
        c_index_%=maxcap_;//维持环形特性
        Unlock(c_mutex_);

        V(pspace_sem_);//消费了数据，空间就增多了
    }
    ~RingQueue()
    {
        sem_destroy(&cdata_sem_);
        sem_destroy(&pspace_sem_);
        pthread_mutex_destroy(&c_mutex_);
        pthread_mutex_destroy(&p_mutex_);
    }
  
private:
    vector<T> ringqueue_;//用数组模拟环形队列
    int maxcap_;//环形队列的最大容量

    int c_index_;//消费者的下标
    int p_index_;//生产者的下标

    sem_t cdata_sem_;//消费者关注的数据资源
    sem_t pspace_sem_;//生产者关注的空间资源

    pthread_mutex_t c_mutex_;
    pthread_mutex_t p_mutex_;
};